package com.kb.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kb.domain.icQuote.QueryTO;
import com.kb.entity.icQuote.Token;
import com.kb.entity.shtQuote.GoodsData;
import com.kb.mapper.mysql.icQuote.TokenMapper;
import com.kb.service.SHTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DS("master")
@Service
@Slf4j
public class SHTServiceImpl implements SHTService {


    @Resource
    private TokenMapper tokenMapper;

    @Resource
    private TokenMapper mapper;
    private String getToken(Integer type){
        QueryWrapper<Token> wrapper=new QueryWrapper();
        wrapper.eq("type",type);

        Token existingToken=tokenMapper.selectOne(wrapper);

        if(existingToken!=null){
            return existingToken.getToken();
        }else{
            return updateToken();
        }



    }
    @Override
    public String updateToken() {
        try {
            // URL of the API endpoint
            String url = "http://t.bomman.com/api/mall-auth/externalAuth/token";

            // Creating the HTTP POST request
            HttpResponse response = HttpRequest.post(url)
                    .header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0")
                    .body("account=kingbrother&password=6046B485926D49A3977E50BB80D5783B")
                    .execute();

            // Getting the response body
            String responseBody = response.body();


            // Parsing the response to extract accessToken using Hutool JSONUtil
            JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
            String accessToken = jsonResponse.getJSONObject("data").getStr("accessToken");

            Long expire = jsonResponse.getJSONObject("data").getLong("expiresIn");

            if(StringUtils.isNotBlank(accessToken)&&expire!=null){
                QueryWrapper<Token> wrapper=new QueryWrapper();
                wrapper.eq("type",2);
                Token existingToken=mapper.selectOne(wrapper);

                if (existingToken == null) {
                    Token newToken = new Token();
                    newToken.setToken(accessToken);
                    newToken.setExpireTime(expire);
                    newToken.setType(2);
                    mapper.insert(newToken);
                } else {
                    existingToken.setExpireTime(expire);
                    existingToken.setToken(accessToken);
                    mapper.updateById(existingToken);
                }


            }


        return accessToken;

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    @Override
    public List<GoodsData> query(QueryTO to) throws JsonProcessingException {
        Map<String, Object> jsonMap = new HashMap<>();

        String token=getToken(2);

        HttpResponse response = HttpRequest.post("http://t.bomman.com/api/oksht-external/v2/product/search")
                .header("Blade-Auth", "bearer " + token)
                .header("sht-auth", "external-service")
                .body("{\"keyword\": \"" + to.getKeyWord() + "\", \"current\": 1, \"size\": 2000, \"type\": 1}")
                .execute();

        String responseBody = response.body();
        log.info("圣禾堂keyword:{}", to.getKeyWord());
        log.info("圣禾堂返回:{}", responseBody);

//        System.out.println("圣禾堂: " + responseBody);

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(responseBody);
        JsonNode dataNode = rootNode.path("data").path("data");


        if(rootNode.path("code").toString().equals("200")){

            // 解析 data.data 部分的数据

            List<GoodsData> goodsDataList = mapper.readValue(dataNode.toString(), mapper.getTypeFactory().constructCollectionType(List.class, GoodsData.class));

            return goodsDataList;
        }

return null;



    }
}
